package cn.edu.imau.zy.system.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import cn.edu.imau.zy.common.core.entity.student.StStudent;
import cn.edu.imau.zy.common.core.entity.system.SysUser;
import cn.edu.imau.zy.common.core.entity.teacher.TcTeacher;
import cn.edu.imau.zy.system.weChat.WeChatApi;
import cn.edu.imau.zy.system.feign.RemoteStudentService;
import cn.edu.imau.zy.system.form.PasswordForm;
import cn.edu.imau.zy.system.service.ITcTeacherService;
import cn.edu.imau.zy.system.util.PasswordUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.edu.imau.zy.common.annotation.LoginUser;
import cn.edu.imau.zy.common.auth.annotation.HasPermissions;
import cn.edu.imau.zy.common.constant.UserConstants;
import cn.edu.imau.zy.common.core.controller.BaseController;
import cn.edu.imau.zy.common.core.domain.R;
import cn.edu.imau.zy.common.log.annotation.OperLog;
import cn.edu.imau.zy.common.log.enums.BusinessType;
import cn.edu.imau.zy.common.utils.RandomUtil;
import cn.edu.imau.zy.system.service.ISysMenuService;
import cn.edu.imau.zy.system.service.ISysUserService;

import cn.hutool.core.convert.Convert;

/**
 * 用户 提供者
 * 
 * @author zmr
 * @date 2019-05-20
 */
@RestController
@RequestMapping("user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysMenuService sysMenuService;

    @Autowired
    private ITcTeacherService teacherService;

    @Autowired
    private RemoteStudentService studentService;
    @Autowired
    private WeChatApi weChatApi;

    /**
     * 查询用户
     */
    @GetMapping("get/{userId}")
    public SysUser get(@PathVariable("userId") String userId)
    {
        return sysUserService.selectUserById(userId);
    }

    /**
     * 查询用户
     */
    @PostMapping("getByParams")
    public SysUser getByParams(@RequestBody SysUser sysUser)
    {
        return sysUserService.selectUser(sysUser);
    }

    @GetMapping("info")
    public SysUser info(@LoginUser SysUser sysUser)
    {
        sysUser.setButtons(sysMenuService.selectPermsByUserId(Long.valueOf(sysUser.getUserId())));
        return sysUser;
    }

    /**
     * 查询用户
     */
    @GetMapping("find/{username}")
    public SysUser findByUsername(@PathVariable("username") String username)
    {
        return sysUserService.selectUserByLoginName(username);
    }

    /**
     * 查询拥有当前角色的所有用户
     */
    @GetMapping("hasRoles")
    public Set<Long> hasRoles(String roleIds)
    {
        Long[] arr=Convert.toLongArray(roleIds);
        return sysUserService.selectUserIdsHasRoles(arr);
    }

    /**
     * 查询所有当前部门中的用户
     */
    @GetMapping("inDepts")
    public Set<Long> inDept(String  deptIds)
    {
        Long[] arr=Convert.toLongArray(deptIds);
        return sysUserService.selectUserIdsInDepts(arr);
    }

    /**
     * 查询用户列表
     */
    @GetMapping("list")
    public R list(SysUser sysUser)
    {
        startPage();
        return result(sysUserService.selectUserList(sysUser));
    }

    /**
     * 批量生成老师帐号
     */
    @PostMapping("createTeachers")
    public R createTeachers(@LoginUser SysUser user)
    {
        List<TcTeacher> teachers = teacherService.getNoLoginList();
        List<SysUser> users = new ArrayList<>();
        for (TcTeacher teacher:teachers) {
            SysUser userItem = new SysUser();
            //相同信息 默认密码000000
            userItem.setUserType("2");
            userItem.setStatus("0");
            userItem.setDelFlag("0");
            userItem.setCreateBy(user.getUserId());
            userItem.setCreateTime(new Date());
            //差异信息
            userItem.setUserId(teacher.getTeacherId());
            userItem.setUserName(teacher.getName());
            userItem.setDeptId(teacher.getDeptId());
            userItem.setLoginName(teacher.getJobNumber());
            userItem.setEmail(teacher.getEmail());
            userItem.setPhonenumber(teacher.getTelphone());
            userItem.setRemark("教师"+teacher.getName());
            userItem.setSalt(RandomUtil.randomStr(6));
            userItem.setPassword(PasswordUtil.encryptPassword(userItem.getLoginName(), teacher.getJobNumber() + "@imau", userItem.getSalt()));
            List<Long> roles = new ArrayList<>();
            roles.add(3L);
            roles.add(4L);
            userItem.setRoleIds(roles);
            users.add(userItem);
        }
        if(users.size()==0){
            return R.error("没有需要创建的帐号");
        }
        //保存列表
        int rows = sysUserService.createList(users);
        return rows > 0 ? R.ok(rows+"个教师帐号被创建"):R.error();
    }


    /**
     * 批量生成学生帐号
     */
    @PostMapping("createStudents")
    public R createStudents(@LoginUser SysUser user)
    {
        List<StStudent> stStudents = studentService.getNoLoginList();
        List<SysUser> users = new ArrayList<>();
        for (StStudent student:stStudents) {
            SysUser userItem = new SysUser();
            //相同信息 默认密码000000
            userItem.setUserType("1");
            userItem.setStatus("0");
            userItem.setDelFlag("0");
            userItem.setCreateBy(user.getUserId());
            userItem.setCreateTime(new Date());
            //差异信息
            userItem.setUserId(student.getStudentId().toString());
            userItem.setUserName(student.getStudentName());
            userItem.setDeptId(student.getDeptId());
            userItem.setLoginName(student.getStudentNum());
            userItem.setEmail(student.getEmail());
            userItem.setPhonenumber(student.getPhoneNumber());
            userItem.setRemark("学生"+student.getStudentName());
            userItem.setSalt(RandomUtil.randomStr(6));

            String password = "000000";
            if (student.getIdCard() != null && student.getIdCard().length() == 18) {
                password = student.getIdCard().substring(11, 17);
            }
            password += "@imau";
            userItem.setPassword(PasswordUtil.encryptPassword(userItem.getLoginName(), password, userItem.getSalt()));
            List<Long> roles = new ArrayList<>();
            roles.add(5L);
            userItem.setRoleIds(roles);
            users.add(userItem);
        }
        if(users.size()==0){
            return R.error("没有需要创建的帐号");
        }

        //保存列表
        int rows = sysUserService.createList(users);
        return rows > 0 ? R.ok(rows+"个学生帐号被创建"):R.error();
    }

    /**
     * 新增保存用户
     */
    @HasPermissions("system:user:add")
    @PostMapping("save")
    @OperLog(title = "用户管理", businessType = BusinessType.INSERT)
    public R addSave(@RequestBody SysUser sysUser)
    {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(sysUserService.checkLoginNameUnique(sysUser.getLoginName())))
        {
            return R.error("新增用户'" + sysUser.getLoginName() + "'失败，登录账号已存在");
        }
        else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(sysUser)))
        {
            return R.error("新增用户'" + sysUser.getLoginName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(sysUserService.checkEmailUnique(sysUser)))
        {
            return R.error("新增用户'" + sysUser.getLoginName() + "'失败，邮箱账号已存在");
        }
        sysUser.setUserId(IdUtil.getSnowflake(1,1).nextIdStr());
        sysUser.setSalt(RandomUtil.randomStr(6));
        sysUser.setPassword(
                PasswordUtil.encryptPassword(sysUser.getLoginName(), sysUser.getPassword(), sysUser.getSalt()));
        sysUser.setCreateBy(getLoginName());
        return toAjax(sysUserService.insertUser(sysUser));
    }

    /**
     * 修改保存用户
     */
    @HasPermissions("system:user:edit")
    @OperLog(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("update")
    public R editSave(@RequestBody SysUser sysUser)
    {
        if (null != sysUser.getUserId() && SysUser.isAdmin(sysUser.getUserId()))
        {
            return R.error("不允许修改超级管理员用户");
        }
        else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(sysUser)))
        {
            return R.error("修改用户'" + sysUser.getLoginName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(sysUserService.checkEmailUnique(sysUser)))
        {
            return R.error("修改用户'" + sysUser.getLoginName() + "'失败，邮箱账号已存在");
        }
        return toAjax(sysUserService.updateUser(sysUser));
    }

    /**
     * 修改用户信息
     * @param sysUser
     * @return
     * @author zmr
     */
    @HasPermissions("system:user:edit")
    @PostMapping("update/info")
    @OperLog(title = "用户管理", businessType = BusinessType.UPDATE)
    public R updateInfo(@RequestBody SysUser sysUser)
    {
        return toAjax(sysUserService.updateUserInfo(sysUser));
    }

    /**
     * 记录登陆信息
     * @param sysUser
     * @return
     * @author zmr
     */
    @PostMapping("update/login")
    public R updateLoginRecord(@RequestBody SysUser sysUser)
    {
        return toAjax(sysUserService.updateUserInfo(sysUser));
    }

    @HasPermissions("system:user:resetPwd")
    @OperLog(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    public R resetPwdSave(@RequestBody SysUser user)
    {
//        if (null != user.getUserId() && SysUser.isAdmin(user.getUserId()))
//        {
//            return R.error("不允许修改超级管理员用户");
//        }
        user.setSalt(RandomUtil.randomStr(6));
        user.setPassword(PasswordUtil.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        return toAjax(sysUserService.resetUserPwd(user));
    }

//    @HasPermissions("system:user:resetPwd")
    @OperLog(title = "修改密码", businessType = BusinessType.UPDATE)
    @PostMapping("/changePwd")
    public R changePwdSave(@LoginUser SysUser user, @RequestBody PasswordForm form)
    {
        if(PasswordUtil.matches(user,form.getPassword())){
            user.setSalt(RandomUtil.randomStr(6));
            user.setPassword(PasswordUtil.encryptPassword(user.getLoginName(), form.getNewPassword(), user.getSalt()));
            return toAjax(sysUserService.resetUserPwd(user));
        }
        return R.error("密码验证失败");
    }

    /**
     * 修改状态
     * @return
     * @author zmr
     */
    @HasPermissions("system:user:edit")
    @PostMapping("status")
    @OperLog(title = "用户管理", businessType = BusinessType.UPDATE)
    public R status(@RequestBody SysUser user)
    {
        if (null != user.getUserId() && SysUser.isAdmin(user.getUserId()))
        {
            return R.error("不允许修改超级管理员用户");
        }
        return toAjax(sysUserService.changeStatus(user));
    }

    /**
     * 删除用户
     * @throws Exception 
     */
    @HasPermissions("system:user:remove")
    @OperLog(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("remove")
    public R remove(String ids) throws Exception
    {
        return toAjax(sysUserService.deleteUserByIds(ids));
    }

    /**
     * 绑定微信
     */
    @OperLog(title = "绑定微信", businessType = BusinessType.GRANT)
    @PostMapping("bind/{code}")
    public R remove(@LoginUser SysUser user, @PathVariable("code") String code) {
//        String resstr = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session?appid=wx3d59d99ca334702c&secret=5d7287f371c5eddceb5d91d01a2381ea&js_code="+code+"&grant_type=authorization_code");
        JSONObject res = JSONObject.parseObject(weChatApi.jscode2session(code));
        if (res.get("openid") != null) {
            SysUser userParams = new SysUser();
            userParams.setOpenId(res.get("openid").toString());
//            if(user.getOpenId() != null){
//                return R.error("绑定失败,该帐号已绑定微信！如不是您本人操作，请联系管理员");
//            }
            if (sysUserService.selectUser(userParams) != null) {
                return R.error("绑定失败，该微信已绑定帐号");
            }
            SysUser userUpdate = new SysUser();
            userUpdate.setUserId(user.getUserId());
            userUpdate.setOpenId(res.get("openid").toString());
            return toAjax(sysUserService.updateUserInfo(userUpdate));
        }
        return R.error("绑定失败，未获取到微信信息");
    }
}
